<%--
  Created by IntelliJ IDEA.
  User: 您的名字
  Version: 1.0
 --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
    <title>EasyUI CRUD 示例页面</title>
    <meta charset="UTF-8">
    <base href="<%=request.getContextPath()%>/">
    <!-- 引入 EasyUI 的默认主题样式 -->
    <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/bootstrap/easyui.css">
    <!-- 引入 EasyUI 的图标样式 -->
    <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/icon.css">
    <!-- 引入自定义的公共CSS -->
    <link rel="stylesheet" type="text/css" href="static/css/common.css"/>
    <!-- 引入 EasyUI 默认的 jQuery（无需单独引入 jQuery） -->
    <script src="static/js/easyui/jquery.min.js"></script>
    <!-- 引入 EasyUI 的核心 JS 文件 -->
    <script src="static/js/easyui/jquery.easyui.min.js"></script>
    <!-- 引入 EasyUI 的中文语言包 -->
    <script src="static/js/easyui/locale/easyui-lang-zh_CN.js"></script>
    <!-- 引入自定义的公共脚本 -->
    <script src="static/js/owner/common.js"></script>
    <script src="static/js/owner/axios.min.js"></script>
    <!-- 引入自定义的公共脚本 -->
    <script src="static/js/owner/dataGrid.js"></script>
    <script src="static/js/owner/moment.min.js"></script>
    <!-- daterangepicker 是一个日期范围选择插件，支持选择开始和结束日期 -->
    <link rel="stylesheet" href="static/css/daterangepicker.css">
    <!-- 引入 daterangepicker 的脚本文件 -->
    <script src="static/js/owner/daterangepicker.js"></script>
    <!-- 引入 ECharts 图表库 -->
    <script src="static/js/owner/echarts.min.js"></script>
    <script src="static/js/owner/echarts-gl.min.js"></script>
    <!-- 引入 UEditor 相关文件 -->
    <script type="text/javascript" src="static/js/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" src="static/js/ueditor/ueditor.all.js"></script>
    <script type="text/javascript" src="static/js/ueditor/lang/zh-cn/zh-cn.js"></script>
    <!-- 添加UEditor服务器配置 -->
    <script type="text/javascript">
        window.UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
        window.UEDITOR_CONFIG.serverUrl = "<%=request.getContextPath()%>/ueditor/config"; // 指向后端配置的接口路径
    </script>
</head>
<style>
    .searchDiv {
        /*border: 1px red solid;*/
        display: flex;           /* 启用Flex布局 */
        flex-direction: row;
        gap: 20px;              /* 项目间距 */
        margin: 20px 10px 5px 10px;
        flex-wrap: wrap;
    }
    .operationBtn {
        margin-top: 20px;
        margin-bottom: 10px;
    }
    .item {
        display: flex;          /* 启用Flex布局 */
        align-items: center;    /* 垂直居中 */
        gap: 10px;              /* 项目间距 */
    }
    label {/*标签列对齐*/
        font-weight: bold;
    }

    .daterange {
        width: 220px !important;
    }

    /* 添加统计图表的样式 */
    .charts-container {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        padding: 10px;
    }

    .chart-box {
        flex: 1;
        min-width: 400px;
        height: 300px;
        margin: 10px;
        background-color: #fff;
        border-radius: 4px;
    }

    /* 图标展示对话框样式 */
    .icons-container {
        display: flex;
        flex-direction: column;
        padding: 10px;
    }

    /* 图标搜索和分类区域 */
    .icons-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
    }

    .icons-search {
        width: 250px;
    }

    .icons-tabs {
        display: flex;
        gap: 10px;
        margin-bottom: 15px;
    }

    .icon-tab {
        padding: 6px 12px;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.3s;
    }

    .icon-tab:hover {
        background-color: #f5f5f5;
    }

    .icon-tab.active {
        background-color: #1976d2;
        color: white;
    }

    /* 图标展示区域 */
    .icons-content {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        max-height: 350px;
        overflow-y: auto;
    }

    .icon-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100px;
        height: 90px;
        padding: 10px 5px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;
        background-color: #fff;
        box-shadow: 0 1px 3px rgba(0,0,0,0.12);
    }

    .icon-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 3px 6px rgba(0,0,0,0.16);
        background-color: #f8f9fa;
    }

    .icon-display {
        width: 32px;
        height: 32px;
        margin-bottom: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .icon-name {
        font-size: 12px;
        text-align: center;
        word-break: break-all;
        color: #555;
    }

    /* 图标提示效果 */
    .icon-tooltip {
        position: fixed;
        background-color: #333;
        color: white;
        padding: 5px 10px;
        border-radius: 4px;
        font-size: 12px;
        z-index: 9999;
        display: none;
    }

    /* 无图标提示 */
    .no-icons-found {
        width: 100%;
        padding: 30px;
        text-align: center;
        color: #999;
        font-size: 14px;
    }

    /* 新增/编辑对话框布局 */
    .form-container {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        padding: 10px;
    }

    .form-item {
        flex: 0 0 calc(50% - 15px);
        display: flex;
        flex-direction: row;  /* 改为横向排列 */
        align-items: center;  /* 垂直居中对齐 */
        margin-bottom: 15px;
    }

    .form-item label {
        width: 80px;          /* 标签固定宽度 */
        margin-right: 10px;   /* 标签右侧间距 */
        text-align: right;    /* 标签右对齐 */
        color: #333;
        white-space: nowrap; /* 防止标签换行 */
    }

    .form-item .input-wrapper {
        flex: 1;              /* 输入框占据剩余空间 */
    }

    .form-item-full {
        flex: 0 0 100%;
    }

    /* 移动设备响应式布局 */
    @media (max-width: 768px) {
        .form-item {
            flex: 0 0 100%;
        }
    }

    /* 富文本编辑器样式 */
    .editor-container {
        width: 100%;
        margin-bottom: 15px;
    }
    .form-item-full {
        flex: 0 0 100%;
        display: flex;
        flex-direction: row;
        align-items: flex-start;
        margin-bottom: 15px;
    }
    .form-item-full label {
        width: 80px;
        margin-right: 10px;
        text-align: right;
        color: #333;
        white-space: nowrap;
        padding-top: 8px;
    }
</style>
<body>
<div id="toolbar">
    <!-- 查询表单 -->
    <form id="searchForm">
        <div class="searchDiv">
            <div class="item">
                <label>事项:</label>
                <input id="item" name="item" class="easyui-textbox">
            </div>
            <div class="item">
                <label>金额:</label>
                <input name="amount" class="easyui-numberbox" precision="2">
            </div>
            <div class="item">
                <label>交易类型:</label>
                <input id="type" name="type" class="easyui-combobox">
            </div>
            <div class="item">
                <label>分类:</label>
                <input id="category" name="category" class="easyui-combobox">
            </div>
            <div class="item">
                <label>创建时间:</label>
                <input id="createTime" name="createTime" class="easyui-textbox daterange">
            </div>

            <div class="searchBtn">
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-search" onclick="searchData()">查询</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" onclick="resetSearch()">重置</a>
            </div>
        </div>
    </form>
    <!-- 操作按钮 -->
    <div class="operationBtn">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="openDialog()">新增</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editRecord()">编辑</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="deleteWallet()">删除</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="batchDeleteWallet()">批量删除</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="excelDoc('myWallet/exportExcel', {selectField: id})">导出Excel</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-redo" plain="true" onclick="openImportDialog()">导入Excel</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-large-chart" plain="true" onclick="openChartsDialog()">统计图表</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-help" plain="true" onclick="openIconsDialog()">图标大全</a>
    </div>
</div>

<!-- 数据表格 -->
<table id="datagrid" class="easyui-datagrid">
    <thead data-options="frozen:true"><%--冻结列--%>
        <tr>
            <!-- 复选框 -->
            <th data-options="field:'ck',checkbox:true"></th>
            <th data-options="field:'id',width:100">记录ID</th>
            <th data-options="field:'item',width:200">事项描述</th>
        </tr>
    </thead>
    <thead>
        <tr>
            <th data-options="field:'amount',width:120, formatter:currencyFormatter, styler:disburseStyler">金额</th>
            <th data-options="field:'type',width:80,formatter:function(value,row,index) {return generalFormatter(value, row, index, {1:'支出','2':'收入','3':'转账','4':'退款'}, '未知');}">交易类型</th>
            <th data-options="field:'category',width:80,formatter:function(value,row,index) {return generalFormatter(value, row, index, {1:'餐饮','2':'交通','3':'娱乐','4':'工资','5':'日用品'}, '未知');}">分类</th>
            <th data-options="field:'paymentMethod',width:120,formatter:function(value,row,index) {return generalFormatter(value, row, index, {1:'微信','2':'支付宝','3':'现金','4':'银行卡'}, '未知');}">支付方式</th>
            <th data-options="field:'createTime',width:150,sortable:true, formatter:formatDate">创建时间</th>
            <th data-options="field:'remark',width:200,formatter:formatRemark">备注</th>
            <th data-options="field:'operation',width:180,align:'center',formatter:formatOperation">操作</th>
        </tr>
    </thead>
</table>

<div id="dlg" class="easyui-dialog" style="width:800px" data-options="closed:true,modal:true,border:'thin',buttons:'#dlg-buttons'">
    <form id="dialogForm" method="post" novalidate>
        <div class="form-container">
            <div class="form-item">
                <label>事项描述:</label>
                <div class="input-wrapper">
                    <input name="item" class="easyui-textbox" required="true" style="width:100%">
                </div>
            </div>
            <div class="form-item">
                <label>金额:</label>
                <div class="input-wrapper">
                    <input name="amount" class="easyui-numberbox" precision="2" required="true" style="width:100%">
                </div>
            </div>
            <div class="form-item">
                <label>交易类型:</label>
                <div class="input-wrapper">
                    <input name="type" class="easyui-combobox" style="width:100%">
                </div>
            </div>
            <div class="form-item">
                <label>分类:</label>
                <div class="input-wrapper">
                    <input name="category" class="easyui-combobox" style="width:100%">
                </div>
            </div>
            <div class="form-item">
                <label>支付方式:</label>
                <div class="input-wrapper">
                    <input name="paymentMethod" class="easyui-combobox" style="width:100%">
                </div>
            </div>
            <div class="form-item">
                <label>创建时间:</label>
                <div class="input-wrapper">
                    <input name="createTime" class="easyui-datetimebox" required="true" data-options="formatter:formatter,parser:parser" style="width:100%">
                </div>
            </div>
            <div class="form-item-full">
                <label>备注:</label>
                <div class="input-wrapper editor-container">
                    <textarea name="remark" id="editor" style="width:100%;height:200px;"></textarea>
                </div>
            </div>
        </div>
    </form>
</div>

<div id="dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveWallet()">保存</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">取消</a>
</div>

<!-- 添加统计图表对话框 -->
<div id="chartsDlg" class="easyui-dialog" style="width:1200px;height:450px;padding:10px"
     data-options="closed:true,modal:true,title:'统计图表',border:'thin',buttons:'#chart-dlg-buttons'">
    <div class="charts-container">
        <div class="chart-box" id="pieChart"></div>
        <div class="chart-box" id="barChart"></div>
        </div>
</div>

<div id="chart-dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#chartsDlg').dialog('close')">关闭</a>
</div>

<!-- 添加导入Excel对话框 -->
<div id="importDlg" class="easyui-dialog" style="width:400px;height:250px;padding:20px"
     data-options="closed:true,modal:true,border:'thin',buttons:'#import-dlg-buttons'">
    <form id="importForm" method="post" enctype="multipart/form-data">
        <div style="margin-bottom:20px;text-align:center;">
            <p style="font-size:14px;margin-bottom:20px;">请选择Excel文件(xlsx格式)</p>
            <input class="easyui-filebox" id="excelFile" name="excelFile" data-options="buttonText:'选择文件',accept:'.xlsx'" style="width:300px;">
        </div>
        <div style="margin-top:20px;text-align:center;">
            <a href="javascript:void(0)" class="easyui-linkbutton" style="margin-right:20px;" onclick="downloadTemplate()">下载模板</a>
        </div>
    </form>
</div>

<div id="import-dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="importExcel()">导入</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#importDlg').dialog('close')">取消</a>
</div>

<!-- 添加图标大全对话框 -->
<div id="iconsDlg" class="easyui-dialog" style="width:850px;height:550px;padding:15px"
     data-options="closed:true,modal:true,title:'EasyUI 图标大全',border:'thin',buttons:'#icons-dlg-buttons'">
    <div class="icons-container" id="iconsContainer">
        <div class="icons-header">
            <div class="icons-search">
                <input id="iconSearch" class="easyui-searchbox" style="width:100%"
                       data-options="prompt:'搜索图标...',searcher:searchIcons">
            </div>
            <div>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload"
                   onclick="resetIconSearch()">重置</a>
            </div>
        </div>
        <div class="icons-tabs" id="iconTabs">
            <!-- 分类标签将通过JS动态生成 -->
        </div>
        <div class="icons-content" id="iconsContent">
            <!-- 图标将通过JS动态生成 -->
        </div>
    </div>
</div>

<div id="icons-dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#iconsDlg').dialog('close')">关闭</a>
</div>

<!-- 图标提示元素 -->
<div class="icon-tooltip" id="iconTooltip"></div>

<!-- 添加详情查看窗口对话框 -->
<div id="detailDlg" class="easyui-window" style="width:850px;height:550px;padding:0px;"
     data-options="closed:true,modal:true,title:'详情查看',border:'thin',shadow:true,inline:true,collapsible:false,minimizable:false,maximizable:false,closable:true">
    <div class="detail-container" style="padding:15px;height:100%;overflow:auto;">
        <div class="detail-header">
            <h2 id="detail-title" style="margin-top:0;color:#333;border-bottom:1px solid #eee;padding-bottom:10px;"></h2>
        </div>
        <div class="detail-content" style="display:flex;flex-wrap:wrap;margin-top:15px;">
            <div class="detail-item" style="flex:0 0 50%;margin-bottom:15px;">
                <label style="font-weight:bold;display:inline-block;width:80px;text-align:right;">事项:</label>
                <span id="detail-item"></span>
            </div>
            <div class="detail-item" style="flex:0 0 50%;margin-bottom:15px;">
                <label style="font-weight:bold;display:inline-block;width:80px;text-align:right;">金额:</label>
                <span id="detail-amount" style="font-weight:bold;"></span>
            </div>
            <div class="detail-item" style="flex:0 0 50%;margin-bottom:15px;">
                <label style="font-weight:bold;display:inline-block;width:80px;text-align:right;">交易类型:</label>
                <span id="detail-type"></span>
            </div>
            <div class="detail-item" style="flex:0 0 50%;margin-bottom:15px;">
                <label style="font-weight:bold;display:inline-block;width:80px;text-align:right;">分类:</label>
                <span id="detail-category"></span>
            </div>
            <div class="detail-item" style="flex:0 0 50%;margin-bottom:15px;">
                <label style="font-weight:bold;display:inline-block;width:80px;text-align:right;">支付方式:</label>
                <span id="detail-paymentMethod"></span>
            </div>
            <div class="detail-item" style="flex:0 0 50%;margin-bottom:15px;">
                <label style="font-weight:bold;display:inline-block;width:80px;text-align:right;">创建时间:</label>
                <span id="detail-createTime"></span>
            </div>
            <div class="detail-item" style="flex:0 0 100%;margin-top:10px;">
                <label style="font-weight:bold;display:inline-block;width:80px;text-align:right;vertical-align:top;">备注:</label>
                <div id="detail-remark" style="display:inline-block;width:calc(100% - 100px);border:1px solid #eee;min-height:150px;padding:10px;border-radius:4px;"></div>
            </div>
        </div>
        <div class="detail-footer" style="margin-top:25px;text-align:center;">
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="$('#detailDlg').window('close')">关闭</a>
        </div>
    </div>
</div>

</body>

<!-- 定义页面脚本 -->
<script type="text/javascript">
    // 初始化UEditor实例
    var ue;

    $(function () {
        const pageConfig = {
            url: 'myWallet/getData',
            emptyMsg: '暂无数据',
        };

        // 调用公共函数初始化 DataGrid
        initializeDataGrid(pageConfig);

        // 批量初始化所有类名为 daterange 的输入框
        initializeDateRangePickers('.daterange');

        // 初始化交易类型下拉框
        $("input[textboxname='type']").combobox({
            url: 'sysDictData/getInfo?dictType=wallet_type',
            valueField:'dictValue',textField:'dictLabel',
            editable: false,
            prompt: '请选择交易类型',
            panelHeight:'auto',
        })

        // 初始化分类下拉框
        $("input[textboxname='category']").combobox({
            url: 'sysDictData/getInfo?dictType=wallet_category',
            valueField:'dictValue',textField:'dictLabel',
            editable: false,
            prompt: '请选择分类',
            panelHeight:'auto',
        })

        // 初始化支付方式下拉框
        $("input[textboxname='paymentMethod']").combobox({
            url: 'sysDictData/getInfo?dictType=wallet_payment_method',
            valueField:'dictValue',textField:'dictLabel',
            editable: false,
            prompt: '请选择支付方式',
            panelHeight:'auto',
        })

        // 初始化日期范围选择器
        $('#dateRange').textbox({
            icons: [{
                iconCls: 'icon-clear',
                handler: function(e) {
                    $(e.data.target).textbox('clear');
                }
            }]
        });
    });

    // 打开新增对话框
    function openDialog() {
        $('#dialogForm').form('clear');
        url = 'myWallet/save';

        // 设置默认支付方式
        $("input[textboxname='paymentMethod']").combobox({
            url: 'sysDictData/getInfo?dictType=wallet_payment_method',
            valueField:'dictValue',textField:'dictLabel',
            editable: false,
            prompt: '请选择支付方式',
            panelHeight:'auto',
            onLoadSuccess: function (data) {
                //设置默认值
                $("input[textboxname='paymentMethod']").combobox('setValue', "1");
            }
        });

        // 初始化编辑器
        initEditor();

        $('#dlg').dialog('open').dialog('setTitle', '新增').window('center');
    }

    // 初始化富文本编辑器
    function initEditor() {
        // 如果已经存在编辑器实例，先销毁
        if (ue) {
            ue.destroy();
        }

        //实例化编辑器
        //建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
        ue = UE.getEditor('editor', {
            zIndex: 10000, // 设置较高的z-index值，确保弹出框在EasyUI对话框之上
            autoHeightEnabled: false, // 自动调整高度
            initialFrameHeight: 200, // 初始化高度
            autoFloatEnabled: true, // 工具栏可浮动
            // 配置上传图片相关选项
            imageActionName: "uploadimage", // 执行上传图片的action名称
            imageFieldName: "upfile", // 提交的图片表单名称
            imageMaxSize: 2048000, // 上传大小限制，单位B，默认2MB
            imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"], // 上传图片格式显示
            imageCompressEnable: true, // 是否压缩图片,默认是true
            imageCompressBorder: 1600, // 图片压缩最长边限制
            imageUrlPrefix: "", // 图片访问路径前缀
            imagePathFormat: "/ueditor/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}" // 上传保存路径
        });
    }

    // 保存钱包记录
    function saveWallet() {
        // 同步编辑器内容到表单
        if (ue) {
            ue.sync();
        }
        //
        //提交方式一: 表反序列化
        console.log("$('#dialogForm').serializeArray()", $('#dialogForm').serializeArray());

        //提交方式二: FormData
        const formData = {
            amount: 23.23,
            category: '2',
            createTime: '2025-05-14 21:48:42',
            item: '哥哥',
            paymentMethod: '1',
            // remark: '<p>分</p>',
            // type: 1
        };
        // $('#dialogForm').serializeArray().forEach(function(item) {
        //     formData[item.name] = item.value;
        // });
        $.ajax({
            url: url,
            type: 'POST',
            // data: formData,
            data: JSON.stringify(formData),
            contentType: 'application/json',
            dataType: 'json',
            success: function (result) {
                if (result.code == 200) {
                    $('#dlg').dialog('close');
                    $('#datagrid').datagrid('reload');
                    $.messager.show({
                        title: '成功',
                        msg: '操作成功',
                        timeout: 2000,
                        showType: 'slide'
                    });
                } else {
                    $.messager.show({
                        title: '错误',
                        msg: result.msg
                    });
                }
            }
        })

        /*$('#dialogForm').form('submit', {
            url: url,
            onSubmit: function () {
                return $(this).form('validate');
            },
            success: function (result) {
                var result = eval('(' + result + ')');
                if (result.code == 200) {
                    $('#dlg').dialog('close');
                    $('#datagrid').datagrid('reload');
                    $.messager.show({
                        title: '成功',
                        msg: '操作成功',
                        timeout: 2000,
                        showType: 'slide'
                    });
                } else {
                    $.messager.show({
                        title: '错误',
                        msg: result.msg
                    });
                }
            }
        });*/
    }

    // 编辑钱包记录
    function editRecord(currentRow) {
        var row = currentRow || $('#datagrid').datagrid('getSelected');
        if (row) {
            $('#dlg').dialog('open').dialog('setTitle', '编辑').window('center');
            $('#dialogForm').form('load', row);
            url = 'myWallet/update?id=' + row.id;

            // 初始化编辑器
            initEditor();

            // 等待编辑器初始化完成后设置内容
            setTimeout(function() {
                if (ue && ue.isReady) {
                    ue.setContent(row.remark || '');
                }
            }, 300);
        } else {
            $.messager.alert('提示', '请选择要编辑的记录！', 'info');
        }
    }

    // 删除钱包记录
    function deleteWallet() {
        var row = $('#datagrid').datagrid('getSelected');
        if (row) {
            $.messager.confirm('确认', '确定要删除该记录吗？', function(r) {
                if (r) {
                    $.post('myWallet/delete', {id: row.id}, function(result) {
                        if (result.code == 200) {
                            $('#datagrid').datagrid('reload');
                        } else {
                            $.messager.show({
                                title: '错误',
                                msg: result.msg
                            });
                        }
                    }, 'json');
                }
            });
        } else {
            $.messager.alert('提示', '请选择要删除的记录！', 'info');
        }
    }

    // 批量删除钱包记录
    function batchDeleteWallet() {
        var rows = $('#datagrid').datagrid('getSelections');
        if (rows.length > 0) {
            $.messager.confirm('确认', '确定要批量删除这些记录吗？', function(r) {
                if (r) {
                    var ids = [];
                    for (var i = 0; i < rows.length; i++) {
                        ids.push(rows[i].id);
                    }

                    $.ajax({
                        url: 'myWallet/batchDelete',
                        type: 'post',
                        data: {ids: ids.join(',')},
                        dataType: 'json',
                        success: function(result) {
                            if (result.code == 200) {
                                $('#datagrid').datagrid('reload');
                                $.messager.show({
                                    title: '成功',
                                    msg: '成功删除' + result.extend.data + '条记录',
                                    timeout: 2000,
                                    showType: 'slide'
                                });
                            } else {
                                $.messager.show({
                                    title: '错误',
                                    msg: result.msg
                                });
                            }
                        }
                    });
                }
            });
        } else {
            $.messager.alert('提示', '请至少选择一条要删除的记录！', 'info');
        }
    }

    // 金额格式化
    function currencyFormatter(value) {
        return value ? '¥' + value.toFixed(2)  : '-';
    }

    // 支出列样式（红色）
    function disburseStyler(value, row) {
        // 如果是支出类型(1)，则显示为红色
        return (row.type == 1) ? 'color:red;font-weight:bold' : '';
    }

    // 备注格式化
    function formatRemark(value, row) {
        if (!value) return '';
        // 去除HTML标签，提取纯文本
        var textOnly = value.replace(/<[^>]+>/g, '');
        // 截取内容
        var preview = textOnly.length > 30 ? textOnly.substring(0, 30) + '...' : textOnly;
        // 添加悬浮提示
        return '<div title="' + textOnly.replace(/"/g, '&quot;') + '">' + preview + '</div>';
    }

    // 日期格式化
    function formatDate(value) {
        if (value) {
            var date = new Date(value);
            return moment(date).format('YYYY-MM-DD HH:mm');
        }
        return '';
    }

    // 打开导入对话框
    function openImportDialog() {
        $('#importDlg').dialog('open').dialog('setTitle', '导入Excel数据').window('center');
        // 清空原有文件选择
        $('#excelFile').filebox('clear');
    }

    // 下载Excel模板
    function downloadTemplate() {
        window.location.href = 'myWallet/downloadTemplate';
    }

    // 导入Excel
    function importExcel() {
        // 判断是否选择文件
        var file = $('#excelFile').filebox('getValue');
        if (!file) {
            $.messager.alert('提示', '请选择要导入的Excel文件!', 'warning');
            return;
        }

        // 提交表单
        $('#importForm').form('submit', {
            url: 'myWallet/importExcel',
            success: function(result) {
                var result = eval('(' + result + ')');
                if (result.code == 200) {
                    $('#importDlg').dialog('close');
                    $('#datagrid').datagrid('reload');
                    $.messager.show({
                        title: '成功',
                        msg: result.msg || '导入成功！共导入' + result.extend.count + '条数据',
                        timeout: 3000,
                        showType: 'slide'
                    });
                } else {
                    $.messager.alert('错误', result.msg || '导入失败，请检查文件格式！', 'error');
                }
            },
            onSubmit: function() {
                // 显示进度条
                $.messager.progress({
                    title: '请稍候',
                    msg: '正在导入数据...',
                    interval: 500
                });
                return $(this).form('validate');
            },
            onLoadError: function() {
                $.messager.progress('close');
                $.messager.alert('错误', '导入失败，请检查文件格式或网络连接！', 'error');
            },
            onLoadSuccess: function() {
                $.messager.progress('close');
            }
        });
    }

    // 打开统计图表对话框
    function openChartsDialog() {
        $('#chartsDlg').dialog('open').window('center');
        // 获取查询条件用于图表过滤
        var queryParams = {};
        // 请求统计数据
        $.ajax({
            url: 'myWallet/getStatistics',
            type: 'post',
            data: queryParams,
            dataType: 'json',
            success: function(result) {
                if (result.code == 200) {
                    renderPieChart(result.extend.data.categoryData);
                    renderBarChart(result.extend.data.monthlyData);
                }
            },
        });
    }

    // 渲染饼图-分类统计
    function renderPieChart(data) {
        // 初始化ECharts实例
        var myChart = echarts.init(document.getElementById('pieChart'));

        // 配置项
        var option = {
            title: {
                text: '支出分类统计',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 10,
                data: data.map(function(item) { return item.name; })
            },
            series: [
                {
                    name: '支出分类',
                    type: 'pie',
                    radius: '50%',
                    center: ['50%', '60%'],
                    data: data,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        // 使用配置项设置图表
        myChart.setOption(option);
    }

    // 渲染柱状图-月度收支统计
    function renderBarChart(data) {
        // 初始化ECharts实例
        var myChart = echarts.init(document.getElementById('barChart'));

        // 配置项
        var option = {
            title: {
                text: '月度收支统计',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['收入', '支出'],
                top: 30
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    data: data.months
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '金额',
                    axisLabel: {
                        formatter: '¥{value}'
                    }
                }
            ],
            series: [
                {
                    name: '收入',
                    type: 'bar',
                    stack: 'Total',
                    emphasis: {
                        focus: 'series'
                    },
                    itemStyle: { color: '#91cc75' },
                    data: data.income
                },
                {
                    name: '支出',
                    type: 'bar',
                    stack: 'Total',
                    emphasis: {
                        focus: 'series'
                    },
                    itemStyle: { color: '#ee6666' },
                    data: data.expense
                }
            ]
        };

        // 使用配置项设置图表
        myChart.setOption(option);
    }

    // 图标组件
    var IconsComponent = (function() {
        // 私有数据
        var icons = {
            standard: {
                name: '标准图标',
                items: [
                    'icon-add', 'icon-edit', 'icon-clear', 'icon-remove',
                    'icon-save', 'icon-cut', 'icon-ok', 'icon-no', 'icon-cancel',
                    'icon-reload', 'icon-search', 'icon-print', 'icon-help', 'icon-undo',
                    'icon-redo', 'icon-back', 'icon-sum', 'icon-tip', 'icon-filter',
                    'icon-man', 'icon-lock', 'icon-more'
                ]
            },
            mini: {
                name: '迷你图标',
                items: [
                    'icon-mini-add', 'icon-mini-edit', 'icon-mini-refresh'
                ]
            },
            large: {
                name: '大型图标',
                items: [
                    'icon-large-picture', 'icon-large-clipart', 'icon-large-shapes',
                    'icon-large-smartart', 'icon-large-chart'
                ]
            }
        };

        var currentTab = 'all';
        var searchTerm = '';

        // 私有方法
        function getFilteredIcons() {
            var result = [];

            // 如果是搜索所有图标
            if (currentTab === 'all' || !currentTab) {
                Object.keys(icons).forEach(function(category) {
                    icons[category].items.forEach(function(icon) {
                        if (!searchTerm || icon.indexOf(searchTerm) !== -1) {
                            result.push(icon);
                        }
                    });
                });
            } else {
                // 搜索特定分类
                if (icons[currentTab]) {
                    icons[currentTab].items.forEach(function(icon) {
                        if (!searchTerm || icon.indexOf(searchTerm) !== -1) {
                            result.push(icon);
                        }
                    });
                }
            }

            return result;
        }

        // 渲染分类标签
        function renderTabs() {
            var tabsContainer = $('#iconTabs');
            tabsContainer.empty();

            // 添加"全部"标签
            var allTab = $('<div class="icon-tab" data-tab="all">全部图标</div>');
            if (currentTab === 'all') {
                allTab.addClass('active');
            }
            tabsContainer.append(allTab);

            // 添加各分类标签
            Object.keys(icons).forEach(function(category) {
                var tab = $('<div class="icon-tab" data-tab="' + category + '">' + icons[category].name + '</div>');
                if (currentTab === category) {
                    tab.addClass('active');
                }
                tabsContainer.append(tab);
            });

            // 绑定点击事件
            $('.icon-tab').click(function() {
                var tab = $(this).data('tab');
                currentTab = tab;
                $('.icon-tab').removeClass('active');
                $(this).addClass('active');
                renderIcons();
            });
        }

        // 渲染图标
        function renderIcons() {
            var iconsContainer = $('#iconsContent');
            iconsContainer.empty();

            var filteredIcons = getFilteredIcons();

            if (filteredIcons.length === 0) {
                iconsContainer.append('<div class="no-icons-found">没有找到匹配的图标</div>');
                return;
            }

            filteredIcons.forEach(function(iconCls) {
                var iconItem = $('<div class="icon-item" data-icon="' + iconCls + '"></div>');
                var iconDisplay = $('<div class="icon-display"></div>').addClass(iconCls);
                var iconName = $('<div class="icon-name"></div>').text(iconCls);

                iconItem.append(iconDisplay).append(iconName);
                iconsContainer.append(iconItem);

                // 点击复制图标类名
                iconItem.click(function() {
                    copyIconName(iconCls);
                });

                // 鼠标悬停显示提示
                iconItem.hover(
                    function() {
                        showTooltip($(this), '点击复制');
                    },
                    function() {
                        hideTooltip();
                    }
                );
            });
        }

        // 显示提示
        function showTooltip(element, text) {
            var tooltip = $('#iconTooltip');
            var offset = element.offset();

            tooltip.text(text)
                .css({
                    top: offset.top - 30,
                    left: offset.left + element.width()/2 - tooltip.width()/2,
                    display: 'block'
                });
        }

        // 隐藏提示
        function hideTooltip() {
            $('#iconTooltip').hide();
        }

        // 复制图标名称
        function copyIconName(iconName) {
            var textarea = document.createElement('textarea');
            textarea.value = iconName;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);

            // 显示复制成功提示
        $.messager.show({
                title: '复制成功',
                msg: '已复制图标类名: ' + iconName,
                timeout: 1500,
            showType: 'slide'
        });
        }

        // 公共接口
        return {
            // 初始化组件
            init: function() {
                renderTabs();
                renderIcons();
            },

            // 搜索图标
            search: function(value) {
                searchTerm = value;
                renderIcons();
            },

            // 重置搜索
            reset: function() {
                searchTerm = '';
                currentTab = 'all';
                this.init();
                $('#iconSearch').searchbox('clear');
            }
        };
    })();

    // 打开图标大全对话框
    function openIconsDialog() {
        $('#iconsDlg').dialog('open').window('center');
        IconsComponent.init();
    }

    // 搜索图标
    function searchIcons(value) {
        IconsComponent.search(value);
    }

    // 重置图标搜索
    function resetIconSearch() {
        IconsComponent.reset();
    }

    // 操作列格式化函数
    function formatOperation(value, row, index) {
        if (row.isFooter) return;
        var html = '<a href="javascript:void(0)" onclick="openDialog()" class="easyui-linkbutton operation-btn" plain="true" data-options="iconCls:\'icon-add\'">新增</a>';
        html += '<a href="javascript:void(0)" onclick="editRecord(' + JSON.stringify(row).replace(/"/g, '&quot;') + ')" class="easyui-linkbutton operation-btn" plain="true" data-options="iconCls:\'icon-edit\'">编辑</a>';
        html += '<a href="javascript:void(0)" onclick="viewDetail(' + JSON.stringify(row).replace(/"/g, '&quot;') + ')" class="easyui-linkbutton operation-btn" plain="true" data-options="iconCls:\'icon-search\'">详情</a>';
        html += '<a href="javascript:void(0)" onclick="moveRecord(' + index + ', \'up\')" class="easyui-linkbutton operation-btn" plain="true" data-options="iconCls:\'icon-up\'">上移</a>';
        html += '<a href="javascript:void(0)" onclick="moveRecord(' + index + ', \'down\')" class="easyui-linkbutton operation-btn" plain="true" data-options="iconCls:\'icon-down\'">下移</a>';
        return html;
    }

    // 上移下移记录
    function moveRecord(index, direction) {
        var rows = $('#datagrid').datagrid('getRows');
        var totalRows = rows.length;

        // 不允许第一行上移或最后一行下移
        if ((direction === 'up' && index === 0) ||
            (direction === 'down' && index === totalRows - 1)) {
            $.messager.show({
                title: '操作提示',
                msg: direction === 'up' ? '已经是第一条记录，无法上移！' : '已经是最后一条记录，无法下移！',
                timeout: 2000,
                showType: 'slide'
            });
            return;
        }

        // 计算交换的位置
        var targetIndex = direction === 'up' ? index - 1 : index + 1;

        // 获取当前行和目标行数据
        var currentRow = rows[index];
        var targetRow = rows[targetIndex];

        // 交换数据
        rows[index] = targetRow;
        rows[targetIndex] = currentRow;

        // 刷新表格显示
        $('#datagrid').datagrid('loadData', rows);

        // 选中移动后的行
        $('#datagrid').datagrid('selectRow', targetIndex);

        $.messager.show({
            title: '操作成功',
            msg: direction === 'up' ? '记录上移成功！' : '记录下移成功！',
            timeout: 1500,
            showType: 'slide'
        });
    }

    // 修改查看详情函数
    function viewDetail(row) {
        // 设置窗口标题
        $('#detailDlg').window({
            title: '详情查看 - ' + row.item,
            // 添加滑动效果
            openAnimation: 'slide',
            openDuration: 600,
            closeAnimation: 'slide',
            closeDuration: 600,
            onBeforeOpen: function() {
                $(this).window('move', {
                    left: $(document).width()
                });
            },
            onOpen: function() {
                $(this).window('center');
            }
        });

        // 填充数据到详情页
        $('#detail-title').text(row.item);
        $('#detail-item').text(row.item);

        // 根据类型设置金额颜色（支出显示为红色）
        var amountText = currencyFormatter(row.amount);
        $('#detail-amount').text(amountText);
        if (row.type == 1) { // 支出
            $('#detail-amount').css('color', 'red');
        } else if (row.type == 2) { // 收入
            $('#detail-amount').css('color', 'green');
        } else {
            $('#detail-amount').css('color', '');
        }

        // 读取配置项的值
        var typeText = '', categoryText = '', paymentMethodText = '';

        // 交易类型
        var typeMap = {1:'支出',2:'收入',3:'转账',4:'退款'};
        typeText = typeMap[row.type] || '未知';
        $('#detail-type').text(typeText);

        // 分类
        var categoryMap = {1:'餐饮',2:'交通',3:'娱乐',4:'工资',5:'日用品'};
        categoryText = categoryMap[row.category] || '未知';
        $('#detail-category').text(categoryText);

        // 支付方式
        var paymentMethodMap = {1:'微信',2:'支付宝',3:'现金',4:'银行卡'};
        paymentMethodText = paymentMethodMap[row.paymentMethod] || '未知';
        $('#detail-paymentMethod').text(paymentMethodText);

        // 创建时间
        $('#detail-createTime').text(formatDate(row.createTime));

        // 备注（富文本内容）
        $('#detail-remark').html(row.remark || '<span style="color:#999;">无备注信息</span>');

        // 打开详情窗口
        $('#detailDlg').window('open');
    }


    // 在datagrid初始化后，处理操作列按钮渲染
    $(function() {
        // 处理表格渲染完成后的操作列按钮渲染
        $('#datagrid').datagrid({
            onLoadSuccess: function() {
                $('.easyui-linkbutton').linkbutton();
            }
        });
    });
</script>
</body>
</html>
